package com.neu.day01;

import com.neu.api.vo.UserVO;
import org.junit.jupiter.api.Test;

import java.sql.*;

public class JDBCDemo {

    //jdbc步骤
       //添加驱动
       //注册驱动
       //获取连接对象
       //获取操作数据库的对象



    static{
        //注册驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

   // @Test
    public void findUserById() {
        int userId =10;
        Connection connection=null;
        PreparedStatement preparedStatement=null;

        ResultSet resultSet=null;
        try {
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/springtest","root","root");

            String sql = "select * from t_user where id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1,userId);

            //里面封装了查询到的数据
            resultSet = preparedStatement.executeQuery();

            UserVO userVO = null;

            if(resultSet.next()){
                //找到一条
                userVO = new UserVO();
                userVO.setName(resultSet.getString("name"));
                userVO.setId(resultSet.getInt("id"));
            }
            System.out.println(userVO);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try{
                //做资源释放
                if(resultSet!=null){
                    resultSet.close();
                }
                if(preparedStatement!=null){
                    preparedStatement.close();
                }
                if(connection!=null){
                    connection.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
